var parentCenterTabs, editRowsNumber, _datasDatagrid, objId, flag,
dialogBannerPic, formBannerPic, sessionID, cityname,
bid, bname, picBtn,opterType,orderIndex
, videobname, dialogBannerVideo, formBannerVideo, videoBtn;
var nodestr="<div style='float:left;' onclick='deleteBannerPic(this)'>" +
		"<img style='width:100px;' class='bannerPicPath' picPath='";

function deleteBannerPic(o) {
	$.messager.confirm('请确认', '您确实要将该图片从轮播图中移除掉吗?该操作不可逆', function(b) {
		if (b) {
			$(o).remove();
		}
	});
}

function addRow() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		_datasDatagrid.datagrid('insertRow', {
			index : 0,
			row : {}
		});
		_datasDatagrid.datagrid('removeEditor', [ 'status']);
		_datasDatagrid.datagrid('beginEdit', 0);
		editRowsNumber = 0;
	}
};

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b) {
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp() + "/admin/banner/delete", {
					ids : ids.join(",")
				}, function(data) {
					if (data && data.result == 1) {
						$.messager.show({
							msg : data.msg,
							title : '系统提示'
						});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
};

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var index = _datasDatagrid.datagrid('getRowIndex', rows[0]);
			_datasDatagrid.datagrid('addEditor', [ {
				field : 'status',
				editor : {
					type : 'combobox',
					options : {
						valueField:'code',
						textField:'name',
						editable:false,
						url:sy.bp() + "/admin/dictionary/listDictionary?name=轮播图状态"
						
					}
				}
			}]);
			_datasDatagrid.datagrid('beginEdit', index);
			editRowsNumber = index;
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
};

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
};

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
};

$(function() {
	parentCenterTabs = parent.centerTabs;
	editRowsNumber = -1;
	_datasDatagrid = $('#_datasDatagrid');
	objId = $('#objId').val();
	flag = $('#flag').val();
	opterType = $('#opterType').val();
	orderIndex=$('#orderIndex').val();
	dialogBannerPic = $('#dialogBannerPic');
	formBannerPic = $('#formBannerPic');
	dialogBannerVideo = $('#dialogBannerVideo');
	formBannerVideo = $('#formBannerVideo');
	sessionID = $('#sessionID').val();
	cityname = $('#cityname');
	bid = $('#bid');
	bname = $('#bname');
	picBtn = $('#picBtn');
	videoBtn = $('#videoBtn');

	picBtn.uploadify({
		method : 'post',
		swf : sy.bp() + '/resources/uploadify/uploadify.swf',
		uploader : sy.bp() + '/admin/fileUpload/upload',
		fileObjName : 'file',
		auto : true,
		formData : {
			'sessionID' : sessionID,
			'uploadPath' : 'banner'
		},
		buttonText : '上传图片',
		queueSizeLimit : 10,
		multi : true,
		removeCompleted : true,
		fileSizeLimit : '10MB',
		fileTypeDesc : 'Image Files',
		fileTypeExts : '*.gif; *.jpg; *.png;',
		onUploadSuccess : function(file, data, response) {
			var resObj = $.parseJSON(data);
			if (resObj.result == 1) {
				var node = nodestr + resObj.obj + "' src='" + sy.bp() + "/resources/upload/banner/" 
				+ resObj.obj + "'/></div>";
				$('#bannerPic').append(node + "&nbsp;&nbsp;");
			} else {
				$.messager.alert('警告', data.msg, 'warning');
			}
		}
	});

	videoBtn.uploadify({
		method : 'post',
		swf : sy.bp() + '/resources/uploadify/uploadify.swf',
		uploader : sy.bp() + '/admin/fileUpload/uploadVideo',
		fileObjName : 'file',
		auto : true,
		formData : {
			'sessionID' : sessionID,
			'uploadPath' : 'video'
		},
		buttonText : '上传视频',
		queueSizeLimit : 10,
		multi : true,
		removeCompleted : true,
		fileSizeLimit : '1GB',
		fileTypeDesc : '视频文件',
		fileTypeExts : '*.3gp; *.mp4; *.avi;*.mov;',
		onUploadSuccess : function(file, data, response) {
			var resObj = $.parseJSON(data);
			if (resObj.result == 1) {
				var node = nodestr + resObj.obj + "' src='" + sy.bp() + "/resources/upload/video/" 
					+ resObj.obj.substring(0, resObj.obj.indexOf('.')) + ".png" + "'/></div>";
				$('#bannerVideo').append(node + "&nbsp;&nbsp;");
			} else {
				$.messager.alert('警告', data.msg, 'warning');
			}
		}
	});

	dialogBannerPic = $('#dialogBannerPic').show().dialog({
		title : '轮播图片管理',
		iconCls : 'icon-feed',
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
		buttons : [ {
			text : '提交',
			handler : function() {
				var picPath = [];
				$.each($('.bannerPicPath'), function(i, v) {
					picPath.push($(v).attr('picPath'));
				});
				if (picPath.length > 9) {
					$.messager.alert('系统提示', '目前每个轮播只支持8张图片!');
				} else {
					var datas = {
						bid : bid.val(),
						orderIndex : $('#orderIndex').val(),
						picPath : picPath.join(",")
					};
					var url = sy.bp() + "/admin/banner/updatePic";
					$.post(url, datas, function(data) {
						if (data && data.result == 1) {
							dialogBannerPic.dialog('close');
							_datasDatagrid.datagrid('reload');
							$.messager.show({
								title : '系统提示',
								msg : '提交成功!',
								timeout : 2000,
								showType : 'slide'
							});
						} else {
							$.messager.alert('系统提示', data.msg);
						}
						;
					}, "json");
				}
			}
		} ]
	});

	dialogBannerVideo = $('#dialogBannerVideo').show().dialog({
		title : '视频管理',
		iconCls : 'icon-feed',
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
		buttons : [ {
			text : '上传',
			handler : function() {
				var picPath = [];
				$.each($('.bannerPicPath'), function(i, v) {
					picPath.push($(v).attr('picPath'));
				});
				if (picPath.length > 9) {
					$.messager.alert('系统提示', '目前每个轮播只支持8段视频!');
				} else {
					var datas = {
						bid : bid.val(),
						orderIndex : $('#orderIndex').val(),
						picPath : picPath.join(",")
					};
					var url = sy.bp() + "/admin/banner/updatePic";
					$.post(url, datas, function(data) {
						if (data && data.result == 1) {
							dialogBannerVideo.dialog('close');
							_datasDatagrid.datagrid('reload');
							$.messager.show({
								title : '系统提示',
								msg : '提交成功!',
								timeout : 2000,
								showType : 'slide'
							});
						} else {
							$.messager.alert('系统提示', data.msg);
						}
						;
					}, "json");
				}
			}
		} ]
	});

	_datasDatagrid.datagrid({
		url : sy.bp() + '/admin/banner/list',
		queryParams : {
			objId : objId,
			flag : flag,
			opterType : opterType,
		},
		fit : true,
		autoRowHeight : true,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [ 10, 20, 30, 40, 50 ],
		nowrap : true,
		border : false,
		idField : 'id',
		sortName : 'createTime',
		sortOrder : 'desc',
		view : sy.myview,
		emptyMsg : '没有查询到相关数据',
		toolbar : [ {
			text : '增加',
			iconCls : 'icon-add',
			handler : addRow
		}, '-', {
			text : '批量删除',
			iconCls : 'icon-remove',
			handler : deleteRow
		}, '-', {
			text : '编辑',
			iconCls : 'icon-edit',
			handler : updateRow
		}, '-', {
			text : '保存',
			iconCls : 'icon-save',
			handler : saveRow
		}, '-', {
			text : '撤销',
			iconCls : 'icon-redo',
			handler : rejectRow
		}, '-', {
			text : '刷新',
			iconCls : 'icon-reload',
			handler : function() {
				_datasDatagrid.datagrid('reload');
			}
		}],
		frozenColumns : [ [ {
			field : 'id',
			title : '编号',
			align : 'center',
			width : 100,
			sortable : true,
			checkbox : true
		}, {
			field : 'name',
			title : 'Banner名称',
			align : 'left',
			width : 400,
			sortable : true,
			editor : {
				type : 'validatebox',
				options : {
					required : true,
					validType : [ 'maxLength[200]' ]
				}
			}
		} ] ],
		columns : [ [ {
			field : 'objName',
			title : '名称',
			align : 'left',
			width : 200,
			sortable : true
		}, {
			field : 'status',
			title : '状态',
			align : 'center',
			width : 100,
			sortable : true,
			formatter : function(value, row) {
				if (value == 1) {
					return "默认";
				} else {
					return "";
				}
			},
			editor : {
				type : 'combobox',
				options : {
					valueField:'code',
					textField:'name',
					editable:false,
					url:sy.bp() + "/admin/dictionary/listDictionary?name=轮播图状态"
					
				}
			}
		}, {
			field : 'createName',
			title : '创建人',
			align : 'center',
			width : 100,
			sortable : true
		}, {
			field : 'createTime',
			title : '创建时间',
			align : 'center',
			width : 100,
			sortable : true
		}  ,{
			field : 'objId',
			title : '人员编号',
			align : 'center',
			width : 100,
			sortable : true,
			hidden:true
		}
		] ],
		onBeforeLoad : function(param) {
			if(flag!=5){
				$('#video').hide();
				$('#pic').hide();
			}
			if (opterType == "0") {
				$('#video').hide();
			} else if (opterType == "1") {
				$('#pic').hide();
			}
		},
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				cityname.val(rowData.objName);
				bid.val(rowData.id);
				bname.val(rowData.name);
				videobname.val(rowData.name);
				$('#opterType').val(rowData.opterType);
				if (opterType == "0") {
					$('#orderIndex').val(0);
					$.post(sy.bp() + '/admin/banner/findByBanner', {
						bid : rowData.id,
						cid : rowData.cid
					}, function(data) {
						if (data) {
							$('#bannerPic').empty();
							$.each(data, function(i, v) {
								var node = nodestr + v.path + "' src='" + sy.bp() + "/resources/upload/banner/" 
									+ v.path + "'/></div>";
								$('#bannerPic').append(node + "&nbsp;&nbsp;");
							});
							dialogBannerPic.dialog('open');
						} else {
							$.messager.alert('系统提示', '加载轮播图片出错,请稍后再试!');
						}
						;
					}, "json");
				} else if (opterType == "1") {
					$('#orderIndex').val(1);
					$.post(sy.bp() + '/admin/banner/findByBanner', {
						bid : rowData.id,
						cid : rowData.cid
					}, function(data) {
						if (data) {
							$('#bannerVideo').empty();
							$.each(data, function(i, v) {
								var node = nodestr + v.path + "' src='" + sy.bp() + "/resources/upload/video/" 
									+ v.path.substring(0, v.path.indexOf('.')) + ".png" + "'/></div>";
								$('#bannerVideo').append(node + "&nbsp;&nbsp;");
							});
							dialogBannerVideo.dialog('open');
						} else {
							$.messager.alert('系统提示', '加载视频出错,请稍后再试!');
						}
						;
					}, "json");
				}

			}
		},
		onRowContextMenu : function(e, rowIndex, rowData) {
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {
				left : e.pageX,
				top : e.pageY
			});
		},
		onAfterEdit : function(rowIndex, rowData, changes) {
			var inserted = _datasDatagrid.datagrid('getChanges', 'inserted');
			var updated = _datasDatagrid.datagrid('getChanges', 'updated');
			if (inserted.length < 1 && updated.length < 1) {
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
				return;
			}
			var url = sy.bp() + '/admin/banner/';
			if (inserted.length > 0) {
				url += 'add';
			} else if (updated.length > 0) {
				url += 'update';
			}
			rowData.objId = objId;
			rowData.flag = flag;
			rowData.opterType=opterType;
			$.post(url, rowData, function(data) {
				if (data && data.result == 1) {
					_datasDatagrid.datagrid('acceptChanges');
					$.messager.show({
						msg : data.msg,
						title : '系统提示'
					});
					_datasDatagrid.datagrid('reload');
				} else {
					_datasDatagrid.datagrid('rejectChanges');
					$.messager.alert('错误', data.msg, 'warning');
				}
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
			}, "json");
		}
	});
});
